/**
 * @(#)YcsQrCodeUtils.java, 2021/12/22.
 * <p/>
 * Copyright 2021 Netease, Inc. All rights reserved.
 * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package site.ycsyxt.common.util;

import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 二维码条形码操作相关工具类
 *
 * @author ycs(15241496739 @ 163.com)
 * @date 2021/12/26
 **/
public class QrBarCodeUtils {

    public static final int LOGO_RATE = 10;

    public static final String FORMAT = "png";

    /**
     * 条形码最小宽度98
     */
    public static final int MIN_BARCODE_WIDTH = 98;

    /**
     * 创建二维码
     *
     * @param content  要写入二维码的内容
     * @param size     二维码大小,通常为300左右
     * @param preColor 图片前景色
     * @param logoImg  logo图片，可以为：null
     * @return BufferedImage, 可以使用 ImageIO.write() 输出
     */
    public static BufferedImage createQRCode(String content, int size, Color preColor, BufferedImage logoImg) {

        try {
            QrCodeGenWrapper.Builder builder = QrCodeGenWrapper.of(content)
                    .setW(size)
                    .setH(size)
                    // 使用检测图片代替检测点
                    //  .setDetectImg(logoPath)
                    // 背景色, 默认白色
                    .setDrawBgColor(0xffffffff)
                    // 前景色
                    .setDrawPreColor(preColor)
                    // 容错率
                    .setErrorCorrection(ErrorCorrectionLevel.M)
                    .setDrawStyle(QrCodeOptions.DrawStyle.CIRCLE)
                    .setDrawEnableScale(true);
            if (logoImg != null) {
                // Logo背景色
                builder.setLogoBgColor(Color.LIGHT_GRAY)
                        .setLogo(logoImg)
                        // 占比, 默认10%
                        .setLogoRate(LOGO_RATE)
                        // Logo样式
                        .setLogoStyle(QrCodeOptions.LogoStyle.CIRCLE);
            }
            return builder.asBufferedImage();
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败！content = "
                    + content + ", size = " + size + ", preColor = " + preColor + "\n" + e);
        }
    }

    /**
     * 解析二维码
     *
     * @param image 二维码图片, 可以使用 ImageIO.read() 创建
     * @return
     */
    public static String parseQRCode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Map<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, hints);
            return result.getText();
        } catch (Exception e) {
            throw new RuntimeException("解析二维码失败！" + "\n" + e);
        }
    }

    /**
     * 把传入的原始图像按高度和宽度进行等比缩放
     *
     * @param srcImage  原始图像
     * @param height    目标高度
     * @param width     目标宽度
     * @param hasFiller 比例不对时是否需要补白：true-补白;
     * @return
     */
    public static BufferedImage scale(BufferedImage srcImage, int height, int width, boolean hasFiller) {
        Image destImage = srcImage.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);
        // 计算比例
        if ((srcImage.getHeight() > height) || (srcImage.getWidth() > width)) {
            // 缩放比例
            double ratio = 0.0;
            if (srcImage.getHeight() > srcImage.getWidth()) {
                ratio = (new Integer(height)).doubleValue() / srcImage.getHeight();
            } else {
                ratio = (new Integer(width)).doubleValue() / srcImage.getWidth();
            }
            AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);
            destImage = op.filter(srcImage, null);
        }
        // 补白
        if (hasFiller) {
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphic = image.createGraphics();
            graphic.setColor(Color.white);
            graphic.fillRect(0, 0, width, height);
            if (width == destImage.getWidth(null)) {
                graphic.drawImage(destImage,
                        0, (height - destImage.getHeight(null)) / 2,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            } else {
                graphic.drawImage(destImage,
                        (width - destImage.getWidth(null)) / 2, 0,
                        destImage.getWidth(null), destImage.getHeight(null),
                        Color.white, null);
            }
            graphic.dispose();
            destImage = image;
        }
        return (BufferedImage) destImage;
    }

    /**
     * 创建条形码
     *
     * @param content
     * @param width
     * @param height
     * @param outputStream
     */
    public static void createBarcode(String content, int width, int height, OutputStream outputStream) {
        width = Math.max(MIN_BARCODE_WIDTH, width);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.EAN_13, width, height, null);
            MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
        } catch (Exception e) {
            throw new RuntimeException("创建条形码失败！content = " + content + "\n" + e);
        }
    }

    /**
     * 解析条形码
     *
     * @param image 条形码图片, 可以使用 ImageIO.read() 创建
     * @return
     */
    public static String parseBarcode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            Result result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            throw new RuntimeException("解析条形码失败！" + "\n" + e);
        }
    }
}
